<template>
  <div class="container">
    <back-header
      class="header"
      :title="(!$id ? '新增' : '编辑') + '视频水印'"
      :needConfirm="true"
    ></back-header>
    <div class="c-block">
      <div class="c-form">
        <el-form
          ref="detailForm"
          :model="formData"
          label-width="100px"
          :rules="rules"
        >
          <el-form-item label="水印名称" prop="watermarkName">
            <el-input
              v-model="formData.watermarkName"
              :maxlength="10"
              style="width: 200px"
              placeholder="请输入水印名称"
            />
          </el-form-item>

          <el-form-item label="水印类型" prop="watermarkType">
            <dict-radio
              v-model="formData.watermarkType"
              dict-key="video_watermark_type"
              @change="onTypeChange"
            />
          </el-form-item>
          <template v-if="formData.watermarkType === 'p'">
            <el-form-item label="水印图片" prop="picPath" key="picPath">
              <CImgUpload
                :path="formData.picPath"
                :actionUrl="actionUrl"
                @uploadSuccess="handleWatermarkSuccess"
                :beforeUpload="beforeWatermarkUpload"
                @remove="handleWatermarkRemove"
              >
                <template #tip>
                  只能上传jpg、jpeg、png、gif格式，不超过20M
                </template>
              </CImgUpload>
            </el-form-item>
          </template>
          <template v-if="formData.watermarkType === 't'">
            <el-form-item label="文字内容" prop="textContent" key="textContent">
              <el-input
                v-model="formData.textContent"
                :maxlength="30"
                style="width: 200px"
                placeholder="请输入文字内容"
              />
            </el-form-item>
            <el-form-item label="文字字体" prop="textFont">
              <dict-select
                v-model="formData.textFont"
                dict-key="video_watermark_font"
              />
            </el-form-item>
            <el-form-item label="文字颜色" prop="textColor">
              <el-color-picker
                v-model="formData.textColor"
              ></el-color-picker>
            </el-form-item>
            <el-form-item label="文字透明度" prop="textAlpha">
              <div class="c-slider">
                <el-slider
                  v-model="alpha"
                  :step="1"
                  :max="100"
                  class="mr-15 w-200"
                >
                </el-slider>
                <el-input-number
                  :controls="false"
                  v-model="alpha"
                  :max="100"
                  :min="0"
                  :step="1"
                  step-strictly
                  class="ninput mr-15"
                />
                %
              </div>
            </el-form-item>
            <el-form-item label="文字字号" prop="+'px'">
              <el-input-number
                :controls="false"
                v-model="formData.textSize"
                :max="100"
                :min="1"
                :step="1"
                step-strictly
                class="ninput"
              />
            </el-form-item>
          </template>
          <el-form-item label="时间线" v-show="false">
            <div class="line">
              <el-switch
                v-model="formData.timeLine"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </div>
            <template v-if="formData.timeLine === 1">
              <div class="line mt-25">
                <span class="mr-15 u-bold">开始时间</span>
                <el-time-picker
                  v-model="formData.timeStart"
                  placeholder="选择开始时间"
                  value-format="HH:mm:ss"
                >
                </el-time-picker>
              </div>
              <div class="line mt-25">
                <span class="mr-15 u-bold">结束方式</span>
                <dict-radio
                  v-model="formData.timeendType"
                  dict-key="video_watermark_timeend_type"
                />
              </div>
              <div class="line mt-25" v-if="formData.timeendType === '1'">
                <span class="mr-15 u-bold">持续时间</span>
                <el-input-number
                  step-strictly
                  :controls="false"
                  v-model="formData.durationSecs"
                  :max="99999"
                  :min="1"
                  :step="1"
                  class="ninput mr-15"
                /><span>秒</span>
              </div>
            </template>
          </el-form-item>

          <el-form-item label="预览尺寸">
            <div class="custom-ratio">
              <div>
                <span class="ration-label"> 宽</span>
                <el-input-number
                  step-strictly
                  :controls="false"
                  v-model="formData.previewW"
                  :max="99999"
                  :min="1"
                  :step="1"
                  class="ninput mr-15"
                  @change="lengthChange('width', $event)"
                />
              </div>
              <div>
                <span class="ration-label">x</span>
                <span class="ration-label">高</span>
                <el-input-number
                  step-strictly
                  :controls="false"
                  v-model="formData.previewH"
                  :max="99999"
                  :min="1"
                  :step="1"
                  class="ninput"
                  @change="lengthChange('height', $event)"
                />
              </div>
              <div class="ratio-checkbox">
                <el-checkbox
                  :true-label="1"
                  :false-label="0"
                  v-model="formData.previewKeepscale"
                  @change="resolutionTypeChange"
                  >约束比例
                </el-checkbox>
              </div>
            </div>
          </el-form-item>
        </el-form>

        <div class="btns">
          <el-button type="primary" @click="saveData">保存</el-button>
          <el-button plain type="primary" @click="btnLeave">取消</el-button>
        </div>
      </div>
      <div class="c-preview" id="preview">
        <div class="preview-label">
          水印预览
          <!-- <span v-if="formData.picPath">
            宽:{{ formData.picW }} 高:{{ formData.picH }} x画布坐标:{{
              formData.watermarkX
            }}
            y画布坐标:{{ formData.watermarkY }} 画布尺寸
            {{ this.formData.previewW }}*{{ this.formData.previewH }}</span
          > -->
        </div>
        <div
          :style="{
            width: dragWidth + 'px',
            height: dragHeight + 'px',
            backgroundColor: '#F6F6F6',
            position: 'relative',
          }"
        >
          <VueDragResize
            ref="drag"
            v-if="isDragInit"
            :x="formData.watermarkX / scale"
            :y="formData.watermarkY / scale"
            :parentW="dragWidth"
            :parentH="dragHeight"
            :sticks="
              formData.watermarkType === 'p'
                ? ['tl', 'tm', 'tr', 'mr', 'br', 'bm', 'bl', 'ml']
                : ['ml', 'mr', 'tm', 'bm']
            "
            :w="formData.picW / scale"
            :h="formData.picH / scale"
            :parentLimitation="true"
            @resizing="resize"
            @dragging="resize"
            :key="dragKey"
            :minw="20"
            :minh="20"
          >
            <template v-if="formData.watermarkType === 't'">
              <div
                :style="[
                  {
                    fontFamily: fontMap[formData.textFont],
                    opacity: formData.textAlpha,
                    color: formData.textColor,
                    fontSize: formData.textSize + 'px',
                  },
                  textStyle,
                ]"
              >
                {{ formData.textContent }}
              </div>
            </template>
            <template v-else>
              <img
                v-if="formData.picPath"
                style="width: 100%; height: 100%"
                :src="filePath + formData.picPath"
              />
            </template>
          </VueDragResize>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BackHeader from "@/components/BackHeader/index";
import DictSelect from "@/components/DictSelect";
import DictRadio from "@/components/DictRadio";
import CImgUpload from "@/components/Upload/CImgUpload";
import { basePath } from "@/utils/request";
import { getToken } from "@/utils/auth";
import { detail, edit, add } from "@/api/system-config/videoWatermark";
import leave from "@/views/_mixins/leave";
import { vaildateInput } from "@/utils/validate";
import VueDragResize from "vue-drag-resize";
const defaultForm = {
  watermarkName: "",
  watermarkType: "p",
  picPath: "",
  textContent: "水印",
  textFont: "微软雅黑",
  textColor: "#000",
  textAlpha: 1,
  textSize: 32,
  timeLine: 0,
  timeStart: "00:00:00",
  timeendType: 0,
  durationSecs: 1,
  previewW: 1920,
  previewH: 1080,
  previewKeepscale: 1,
  watermarkX: 100,
  watermarkY: 100,
  picW: 100,
  picH: 100,
};
export default {
  name: "watermark-video-form",
  components: {
    BackHeader,
    DictSelect,
    DictRadio,
    VueDragResize,
    CImgUpload,
  },
  mixins: [leave],
  data() {
    return {
      filePath,
      fontMap: { 微软雅黑: "Microsoft YaHei", 宋体: "宋体" },
      isDragInit: false,
      dragWidth: 0,
      dragHeight: 0,
      actionUrl: basePath + "watermark/file",
      $id: "",
      ratio: 1,
      formData: { ...defaultForm },
      rules: {
        watermarkName: [
          { required: true, message: "水印名称不能为空" },
          { validator: vaildateInput, trigger: ["blur", "change"] },
        ],
        picPath: [
          { required: true, message: "水印图片不能为空" },
        ],
        textContent: [
          { required: true, message: "文字内容不能为空" },
          { validator: vaildateInput, trigger: ["blur", "change"] },
        ],
      },
      scale: 1,
      dragKey: 0,
    };
  },
  watch: {
    "formData.watermarkType"(val) {
      this.$disResize = true;
    },
  },
  created() {
    this.$id = this.$route.query.id;
  },
  computed: {
    headers() {
      let token = getToken();
      return token ? { Authorization: token } : {};
    },
    textStyle() {
      if (this.formData.watermarkType === "t") {
        return {
          // transform: `scale(${1 / this.scale})`,
          // transformOrigin: "left top",
          lineHeight: 1,
          width: "100%",
          height: "100%",
        };
      }
      return {};
    },
    alpha: {
      get() {
        return +this.formData.textAlpha * 100;
      },
      set(val) {
        this.formData.textAlpha = String(val / 100);
      },
    },
  },
  mounted() {
    this.$id = this.$route.query.id;
    if (this.$id) {
      this.getData();
    } else {
      this.ratio = this.formData.previewW / this.formData.previewH;
      this.initDrag();
    }
    window.addEventListener("resize", this.initDrag);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.initDrag);
  },
  methods: {
    resetDrag() {
      this.dragKey++;
    },
    // 文件上传前的校验 —— 常见的校验有：校验文件类型，文件大小
    beforeWatermarkUpload(file) {
      // 允许上传的文件格式列表
      let acceptList = ["png", "jpg", "jpeg", "gif"];
      // 根据文件名获取文件的后缀名
      let fileType = file.name.split(".").pop().toLowerCase();
      // 判断文件格式是否符合要求
      if (acceptList.indexOf(fileType) === -1) {
        this.$message.error(
          "请按照提示上传文件，不能上传 " + fileType + " 格式!"
        );
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        this.$message.error("上传水印图片大小不能超过 20MB!");
      }
      let reader = new FileReader();
      const that = this;
      reader.onload = function (e) {
        let txt = e.target.result;
        let img = document.createElement("img");
        img.src = txt;
        img.onload = function () {
          that.$width = img.width;
          that.$height = img.height;
        };
      };
      reader.readAsDataURL(file);
    },
    handleWatermarkSuccess(res, file, fileList) {
      this.formData.picPath = res.data;
      this.formData.picW = Math.min(this.$width, this.formData.previewW);
      this.formData.picH = Math.min(this.$height, this.formData.previewH);
      this.initDrag("reset");
    },
    handleWatermarkRemove() {
      this.formData.picPath = "";
      this.formData.picW = 0;
      this.formData.picH = 0;
    },
    getData() {
      detail(this.$id).then((res) => {
        this.formData = res;
        this.ratio = this.formData.previewW / this.formData.previewH;
        this.initDrag();
      });
    },
    saveData() {
      this.$refs.detailForm.validate((valid) => {
        if (!valid) return;
        if (this.formData.watermarkType === "p" && !this.formData.picPath) {
          this.$message.error("请上传水印图片!");
          return;
        }
        if (this.formData.watermarkType === "t" && !this.formData.textContent) {
          this.$message.error("请填写水印内容!");
          return;
        }
        if (this.$id) {
          edit(this.$id, this.formData).then(() => {
            this.$message.success("编辑成功!");
            this.$router.back();
          });
        } else {
          add(this.formData).then(() => {
            this.$message.success("新增成功!");
            this.$router.back();
          });
        }
      });
    },
    lengthChange(type, val) {
      if (this.formData.previewKeepscale) {
        if (type == "width") {
          this.formData.previewH = Math.floor(val / this.ratio);
        }
        if (type == "height") {
          this.formData.previewW = Math.floor(val * this.ratio);
        }
      }
      this.initDrag("reset");
    },
    resolutionTypeChange(type) {
      if (type) {
        if (!this.formData.previewH || !this.formData.previewW) {
          this.formData.previewW = 1920;
          this.formData.previewH = 1080;
        }
        this.ratio = this.formData.previewW / this.formData.previewH;
      }
    },
    async initDrag(type) {
      let dragEl = document.getElementById("preview");
      const padding = 30;
      const mw = dragEl.clientWidth - padding;
      const mh = dragEl.clientHeight - padding;
      const w = this.formData.previewW;
      const h = this.formData.previewH;
      const ratio = w / h;
      let rw, rh;
      if (ratio > 1) {
        rw = mw;
        rh = rw / ratio;
        if (rh > mh) {
          rh = mh;
          rw = rh * ratio;
        }
      } else {
        rh = mh;
        rw = rh * ratio;
      }
      this.dragWidth = rw;
      this.dragHeight = rh;
      this.scale = this.formData.previewW / this.dragWidth;
      if (type === "reset") {
        this.dragKey++;
      }
      if (
        this.formData.picW + this.formData.watermarkX >
        this.formData.previewW
      ) {
        this.formData.picW = this.formData.previewW;
        this.formData.watermarkX = 0;
      }
      if (
        this.formData.picH + this.formData.watermarkY >
        this.formData.previewH
      ) {
        this.formData.picH = this.formData.previewH;
        this.formData.watermarkY = 0;
      }
      this.isDragInit = true;
    },
    resize(newRect) {
      // if (this.$disResize) return;
      this.formData.picW = Math.round(this.$refs.drag.width * this.scale);
      this.formData.picH = Math.round(this.$refs.drag.height * this.scale);
      this.formData.watermarkX = Math.round(this.$refs.drag.left * this.scale);
      this.formData.watermarkY = Math.round(this.$refs.drag.top * this.scale);
      console.log(
        this.formData.picW,
        this.formData.picH,
        this.formData.watermarkX,
        this.formData.watermarkY
      );
    },
    async onTypeChange() {
      await this.$nextTick();
      this.$disResize = false;
      if (this.formData.watermarkType === "t") {
        this.$tempPConfig = {
          watermarkX: this.formData.watermarkX,
          watermarkY: this.formData.watermarkY,
          picW: this.formData.picW,
          picH: this.formData.picH,
        };
        if (this.$tempTConfig) {
          this.formData.watermarkX = this.$tempTConfig.watermarkX;
          this.formData.watermarkY = this.$tempTConfig.watermarkY;
          this.formData.picW = this.$tempTConfig.picW;
          this.formData.picH = this.$tempTConfig.picH;
        } else {
          this.formData.watermarkX = 100;
          this.formData.watermarkY = 100;
          this.formData.picW =600
            // this.formData.previewW -  this.formData.watermarkX;
          this.formData.picH =300
            // this.formData.previewH -  this.formData.watermarkY;
        }
      } else if (this.formData.watermarkType === "p") {
        this.$tempTConfig = {
          watermarkX: this.formData.watermarkX,
          watermarkY: this.formData.watermarkY,
          picW: this.formData.picW,
          picH: this.formData.picH,
        };
        if (this.$tempPConfig) {
          this.formData.watermarkX = this.$tempPConfig.watermarkX;
          this.formData.watermarkY = this.$tempPConfig.watermarkY;
          this.formData.picW = this.$tempPConfig.picW;
          this.formData.picH = this.$tempPConfig.picH;
        } else {
          this.formData.watermarkX = 100;
          this.formData.watermarkY = 100;
          this.formData.picW = 100;
          this.formData.picH = 100;
        }
      }
      this.dragKey++;
    },
  },
};
</script>
<style lang="scss" scoped>
.header {
  margin-bottom: 30px;
}
.container {
  padding: 20px 18px;
  background-color: #fff;
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
}
.custom-ratio {
  display: flex;
}
.ratio-checkbox {
  margin-left: 35px;
  margin-right: 10px;
}
.ninput {
  width: 85px;
}
.ration-label {
  margin-right: 15px;
}
.mt-25 {
  margin-top: 25px;
}
.mr-15 {
  margin-right: 15px;
}
.tip {
  font-weight: 400;
  color: #8d8d8d;
  line-height: 23px;
  font-size: 12px;
}
.c-block {
  display: flex;

  flex: 1;
  height: 0;
}
.btns {
  position: absolute;
  left: 60px;
  bottom: 30px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}
.c-form {
  margin-bottom: 40px;
  overflow: auto;
  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 4px;
  }
  &::-webkit-scrollbar-track-piece {
    background: rgba(200, 200, 200, 0.1);
  }
  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 8px;
    background: rgba(200, 200, 200, 0.5);
  }
}
.u-bold {
  font-weight: bold;
}
.c-preview {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}
.preview-label {
  font-weight: bold;
  height: 20px;
  line-height: 20px;
  position: absolute;
  top: -25px;
  left: 0;
}
.c-slider {
  display: flex;
  align-items: center;
}
.w-200 {
  width: 200px;
}
:deep(.content-container) {
  overflow: hidden;
}
</style>
